package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import io.swagger.annotations.Api;
import jodd.io.FileNameUtil;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author ：Shine
 * @description：
 * @date ：2021/2/2 21:31
 */
@Api(tags = "文件上传接口")
@RestController
@RequestMapping("admin/product")
public class FileUploadController {
    @Value("${fileServer.url}")
    private String fileUrl;

    @PostMapping("fileUpload")
    public Result<String> fileUpload(MultipartFile file) throws Exception {
        //1.读取配置文件信息
        String configFile = this.getClass().getResource("/tracker.conf").getFile();

        String path = null;
        //2.初始化fastDFS服务器
        if (configFile != null) {
            ClientGlobal.init(configFile);

            //3.创建TrackerClient客户端,TrackerServer
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer TrackerServer = trackerClient.getConnection();

            //4.创建storageClient并上传文件
            StorageClient1 storageClient1 = new StorageClient1(TrackerServer, null);

            //获取文件名后缀
            String extFileName = FileNameUtil.getExtension(file.getOriginalFilename());

            //返回文件上传之后的url地址，参数：上传文件字节数组，后缀名
            path = storageClient1.upload_appender_file1(file.getBytes(), extFileName, null);

        }
        System.err.println("文件上传路径:" + fileUrl + path);

        //5.获取上传文件的url

        return Result.ok(fileUrl + path);
    }
}
